#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import os
import sys
import json

def get_gitee_repos(token=None, username=None):
    """获取Gitee账号下有权限的所有仓库"""
    if not token and 'GITEE_TOKEN' in os.environ:
        token = os.environ['GITEE_TOKEN']
    
    if not token:
        print("错误: 需要Gitee个人访问令牌，请设置GITEE_TOKEN环境变量或通过参数传入")
        sys.exit(1)
        
    if not username and 'GITEE_USERNAME' in os.environ:
        username = os.environ['GITEE_USERNAME']
        
    if not username:
        # 获取当前登录用户信息
        headers = {'Authorization': f'token {token}'}
        user_resp = requests.get('https://gitee.com/api/v5/user', headers=headers)
        if user_resp.status_code != 200:
            print(f"错误: 无法获取用户信息，HTTP状态码: {user_resp.status_code}")
            print(user_resp.text)
            print("请设置GITEE_USERNAME环境变量或通过参数传入")
            sys.exit(1)
        username = user_resp.json()['login']
    
    headers = {'Authorization': f'token {token}'}
    all_repos = []
    page = 1
    per_page = 100
    
    # 保存第一个仓库的完整信息，以便分析
    sample_repo = None
    
    while True:
        # 获取用户的仓库（包括私有仓库）
        url = f'https://gitee.com/api/v5/user/repos?access_token={token}&page={page}&per_page={per_page}&type=all'
        resp = requests.get(url)
        
        if resp.status_code != 200:
            print(f"错误: 无法获取仓库列表，HTTP状态码: {resp.status_code}")
            print(resp.text)
            sys.exit(1)
            
        repos = resp.json()
        if not repos:
            break
        
        # 保存第一个仓库信息用于分析
        if page == 1 and repos:
            sample_repo = repos[0]
            # 将样本数据保存到文件，方便分析
            with open('sample_repo.json', 'w') as f:
                json.dump(sample_repo, f, indent=2)
            print("已保存样本仓库数据到 sample_repo.json")
            
        for repo in repos:
            # 尝试直接获取SSH克隆URL
            if 'ssh_url' in repo:
                all_repos.append(repo['ssh_url'])
            else:
                # 如果没有ssh_url字段，则构造一个
                owner = repo['owner']['login']
                repo_name = repo['path']
                ssh_url = f"git@gitee.com:{owner}/{repo_name}.git"
                all_repos.append(ssh_url)
            
        page += 1
        if len(repos) < per_page:
            break
    
    return all_repos

def main():
    # 可以扩展为从命令行参数读取
    gitee_token = os.environ.get('GITEE_TOKEN')
    gitee_username = os.environ.get('GITEE_USERNAME')
    
    # 获取所有仓库URL
    repos = []
    
    try:
        gitee_repos = get_gitee_repos(token=gitee_token, username=gitee_username)
        print(f"已找到 {len(gitee_repos)} 个Gitee仓库")
        repos.extend(gitee_repos)
    except Exception as e:
        print(f"获取Gitee仓库时出错: {e}")
    
    # 将仓库URL写入文件
    with open('repos.txt', 'w') as f:
        for repo in repos:
            f.write(f"{repo}\n")
    
    print(f"共找到 {len(repos)} 个仓库，已写入 repos.txt")

if __name__ == "__main__":
    main() 